package com.browsesoft.synchronserver;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Hashtable;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.browsesoft.Manager;
import com.browsesoft.ManagerGroup;
import com.browsesoft.PropertiesService;

public class SynchronServer extends UnicastRemoteObject implements
		SynchronServerRMI {

	private static final long serialVersionUID = 1L;

	private static SynchronServer self;

	public SynchronServer() throws RemoteException {
		self = this;
	}

	public static SynchronServer getInstance() {
		return self;
	}

	public void add(String tableName, Hashtable attributes)
			throws RemoteException {
		// 根据tableName相应的配置元素
		String table = tableName.toLowerCase();
		NodeList list = this.getConfigElem(table);
		if (list.getLength() > 0) {
			Element elem = (Element) list.item(0);
			String className = this.getClassName(elem);
			String managerName = this.getManagerName(elem);
			// 创建新对象，并加入到相应的管理器中
			Manager manager = ManagerGroup.getManagerGroup().getManager(
					managerName);
			manager.synchronAdd(className, attributes);
		}
	}

	public void update(String tableName, String id, Hashtable attributes)
			throws RemoteException {
		// 根据tableName相应的配置元素
		String table = tableName.toLowerCase();
		NodeList list = this.getConfigElem(table);
		if (list.getLength() > 0) {
			Element elem = (Element) list.item(0);
			String managerName = this.getManagerName(elem);
			// 创建新对象，并加入到相应的管理器中
			Manager manager = ManagerGroup.getManagerGroup().getManager(
					managerName);
			manager.synchronUpdate(id, attributes);
		}
	}

	public void delete(String tableName, String id) throws RemoteException {
		// 根据tableName相应的配置元素
		String table = tableName.toLowerCase();
		NodeList list = this.getConfigElem(table);
		if (list.getLength() > 0) {
			Element elem = (Element) list.item(0);
			String managerName = this.getManagerName(elem);
			// 从对应的管理器中删除
			Manager manager = ManagerGroup.getManagerGroup().getManager(
					managerName);
			manager.synchronRemove(id);
		}
	}

	/**
	 * 根据表明得到管理器名称
	 */
	private String getClassName(Element elem) {
		String result = "";
		// 得到类名＆实体管理器名称
		result = elem.getAttribute("classname");
		return result;
	}

	/**
	 * 根据表明得到管理器名称
	 */
	private String getManagerName(Element elem) {
		String result = "";
		result = elem.getParentNode().getNodeName();
		return result;
	}

	private NodeList getConfigElem(String tableName) {
		// 根据表明从属性文件得到该配置元素
		Document doc = PropertiesService.getDocument();
		return doc.getElementsByTagName(tableName);
	}
}
